// pages/scankd/scankd.ts
import request from '../../utils/request'
const app = getApp<IAppOption>()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        globalData: {},
        isAuth: false,// 是否授权摄像头
        src: '',// 图片地址

        equipmentNo: '',// 设备号
        xm: '',// 姓名
        sfzNo: '',// 身份证号码
        cs: '',// 出生年月
        nl: '',// 年龄
        ys: '',// 医生账号
        pwd: '',// 医生密码
        rentalDays: '1',// 绑定天数
        phone: '',// 手机号码
        xb: 0,// 性别

        // 选择卡类型
        showCardType: false,
        cardActions: [
          {
            name: '身份证',
            type: 'idcard',
          },
          {
            name: '社保卡',
            type: 'social_security_card',
          },
        ],
        selectCardType: '',

        // 设备选择框
        showCheckBox: false,
        deviceList: [],

        // 确认框
        popup: {},
    },

    // 打开卡选择
    changeCard(){
        this.closeCheckBox()
        this.setData({ showCardType: true });
    },
    // 关闭卡选择
    onClose() {
        this.setData({ showCardType: false });
    },
    // 选中卡片
    onSelect(event: any) {
        let obj = event.detail;
        this.setData({selectCardType: obj.type });
        this.uploadPhoto();
    },

    uploadPhoto() { // 拍摄或从相册选取上传
        let that = this;
        wx.chooseMedia({
            count: 1, // 默认9
            mediaType: ['image'],// 文件类型（只能拍摄图片或从相册选择图片）
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            success(res) {
                let tempFiles = res.tempFiles; // 返回选定照片的本地路径列表 
                that.upload(that, tempFiles);
            }
        })
    },
    upload(page, path) { // 上传图片
        let that = this;
        wx.showToast({ icon: "loading", title: "正在上传……", duration: 30000 });
        wx.uploadFile({
            url: app.globalData.baseUrl + '/applet/images/sfznot', //后端接口
            filePath: path[0].tempFilePath,
            name: 'file',
            formData: {
                diary1: that.data.selectCardType,
            },
            header: {
                'Authorization': app.globalData?.access_token || ''
            },
            success(res) {
                if (res.statusCode == 200) {
                    let data = JSON.parse(res.data);
                    if(data.code == 200) {
                        that.setData({
                            sfzNo: data.data.sfzNo,
                            cs: data.data.cs,
                            xb: data.data.xb,
                            xm: data.data.xm,
                            nl: data.data.nl,
                            phone: data.data.phone,
                        });
                    } else {
                        wx.showModal({ title: '识别出错', content: data.msg, showCancel: false });
                    }
                } else {
                    wx.showToast({
                        title: "识别失败，请稍后重试！",
                        icon: 'none',
                        duration: 1500
                    })
                }
            },
            fail(res) {
                wx.showModal({ title: '提示', content: '上传失败！', showCancel: false });
            },
            complete() {
                wx.hideToast(); //隐藏Toast
            }
        })
    },

    // 加载绑定的设备
    getData(){
        let that = this;
        request.get('/applet/bind-info/list?dataType='+app.globalData.dataType).then((res: any) => {
            if(res.data.code === 200) {
                that.setData({
                    deviceList: res.data.data
                }) 
            }
        })
    },
    // 打开/关闭设备号选项框
    openCheckBox(){
        this.setData({ showCheckBox: !this.data.showCheckBox });
    },
    closeCheckBox(){
        this.setData({ showCheckBox: false });
    },
    haldCheckDevice(e : any){
        let equipmentNo = e.currentTarget.dataset.no
        this.setData({ 
            equipmentNo: equipmentNo,
            showCheckBox: false,
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(e: any) {
        const _this = this
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.camera']) {
                    // 用户已经授权
                    _this.setData({
                        isAuth: true
                    })
                } else {
                    // 用户还没有授权，向用户发起授权请求
                    wx.authorize({
                        scope: 'scope.camera',
                        success() { // 用户同意授权
                            _this.setData({
                                isAuth: true
                            })
                        },
                        fail() { // 用户不同意授权
                            _this.openSetting().then(res => {
                                _this.setData({
                                    isAuth: true
                                })
                            })
                        }
                    })
                }
            },
            fail: res => {
                // 获取用户授权信息失败
            }
        })
    },
    // 打开授权设置界面
    openSetting() {
        const _this = this
        let promise = new Promise((resolve, reject) => {
            wx.showModal({
                title: '授权',
                content: '请先授权获取摄像头权限',
                success(res) {
                    if (res.confirm) {
                        wx.openSetting({
                            success(res) {
                                if (res.authSetting['scope.camera']) { // 用户打开了授权开关
                                    resolve(true)
                                } else { // 用户没有打开授权开关， 继续打开设置页面
                                    _this.openSetting().then(res => {
                                        resolve(true)
                                    })
                                }
                            },
                            fail(res) {
                                
                            }
                        })
                    } else if (res.cancel) {
                        _this.openSetting().then(res => {
                            resolve(true)
                        })
                    }
                }
            })
        })
        return promise;
    },

    takePhoto() {
        const ctx = wx.createCameraContext()
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                this.setData({
                    src: res.tempImagePath
                })
                wx.previewImage({
                    current: res.tempImagePath, // 当前显示图片的http链接
                    urls: [res.tempImagePath] // 需要预览的图片http链接列表
                })
            }
        })
    },
    // 扫描设备号二维码
    handleScan() {
        this.closeCheckBox()
        wx.scanCode({
            success: (res) => {
                this.setData({
                    equipmentNo: res.result
                })
            }
        })
    },
    // 设备开单
    handleBtn() {
        this.closeCheckBox()
        const { equipmentNo } = this.data
        const { sfzNo, xb, cs, xm, nl, ys, pwd, rentalDays, phone } = this.data
        

        // 判断参数
        if(!equipmentNo || !xm || !sfzNo || !phone || !rentalDays || !ys ||  
            (!app.globalData.doctorAccount && !pwd)){
            wx.showToast({
                title: '请完整输入信息',
                icon: 'error',
                duration: 2000
            })
            return ;
        }
        const param = {
            patientName: xm,
            gender: xb,
            identityNumber: sfzNo,
            birthday: cs,
            age: nl,
            phone: phone,
            rentalDays: rentalDays,
            userName: ys,
            userPassword: pwd,
            dataType: app.globalData.dataType,
            equipmentNo: equipmentNo // 设备编号
        }

        let that = this;
        wx.showLoading({
            title: '请求中...',
        });
        request.post('/applet/patient/data', param).then((res: any) => {
            wx.hideLoading();
                
            // 保存医生账号信息
            app.globalData.doctorAccount = res.data.data
            wx.setStorageSync('doctorAccount', app.globalData.doctorAccount);
            
            that.setData({
                globalData: app.globalData,
                popup: {
                    idx: Math.random(),
                    show: true,
                    title: '提 示',
                    msg: '患者开单成功！',
                    icon: '../../static/img/smile.png'
                },
                sfzNo: '', 
                xb: 0,
                cs: '',
                xm: '',
                nl: '', 
                ys: app.globalData.doctorAccount, 
                pwd: '',
                rentalDays: '1',
                phone: '',
                equipmentNo: ''
            })
        })
    },

    /**
     * 根据身份证号码查询患者信息
     */
    searchByIdCardNo(){
        if(this.data.sfzNo) {
            let that = this;
            that.setData({
                cs: '',
                xb: 0,
                xm: '',
                nl: '',
                phone: '',
            });
            request.get('/applet/patient/searchByIdCardNo', {idCardNo: this.data.sfzNo}).then((res: any) => {
                let data = res.data.data;
                if(data) {
                    that.setData({
                        sfzNo: data.sfzNo,
                        cs: data.cs,
                        xb: data.xb,
                        xm: data.xm,
                        nl: data.nl,
                        phone: data.phone,
                    });
                }
            });
        } else {
            wx.showToast({
                title: '请先填入身份证号',
                icon: 'error',
                duration: 2000
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            globalData: app.globalData,
            ys: app.globalData.doctorAccount
        });
        
        this.getData();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})